// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()
const _ = db.command // <-- ***新增***

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID;

  try {
    const ordersRes = await db.collection('orders')
      .where({
        _openid: openid
      })
      .orderBy('createTime', 'desc')
      .get();
      
    const orders = ordersRes.data;

    // --- *** 新增：在云函数端计算排队人数 *** ---
    if (orders.length > 0) {
      // 1. 定义计算逻辑
      const enrichQueueAhead = (order) => {
        // 只为“待处理”和“打印中”的订单计算排队
        if (order.printStatus === 'pending' || order.printStatus === 'printing') {
          return db.collection('orders')
            .where({
              printerId: order.printerId,
              printStatus: _.in(['pending', 'printing']),
              createTime: _.lt(order.createTime) // 查找创建时间早于当前订单的
            })
            .count()
            .then(r => ({ ...order, queueAhead: r.total }))
            .catch(() => ({ ...order, queueAhead: 0 }));
        }
        // 已完成或已取消的订单，无需计算排队
        return Promise.resolve({ ...order, queueAhead: 0 });
      };

      // 2. 并行执行所有计算
      const enrichedOrders = await Promise.all(orders.map(enrichQueueAhead));

      // 3. 返回已包含排队人数的数据
      return {
        success: true,
        data: enrichedOrders
      }
    }
    // --- *** 修改结束 *** ---

    return {
      success: true,
      data: orders // (如果订单为空，直接返回空数组)
    }

  } catch (e) {
    console.error('获取订单列表失败', e);
    return {
      success: false,
      error: e.message
    }
  }
}